package com.fdb.smcts.core.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

public class DataFileUtil {

    private static Logger logger = LoggerFactory.getLogger(DataFileUtil.class);

    private static String defaultSeparator = "|";//默认分隔符
    private static String defaultCharacterSet = "UTF-8";//默认字符集

    public static <T> List<T> readTxt(File file, Class<? extends T> clazz, String templateName) throws Exception {
        return readTxt(file, clazz, templateName, defaultCharacterSet);
    }

    @SuppressWarnings("unchecked")
    public static <T> List<T> readTxt(File file, Class<? extends T> clazz, String templateName, String charSet) throws Exception {
        InputStreamReader reader = null;
        BufferedReader br = null;
        try {
            reader = new InputStreamReader(new FileInputStream(file), charSet);
            br = new BufferedReader(reader);
            String line = br.readLine();
            List<T> tList = new ArrayList<T>();
            while (StringUtil.isStrNotEmpty(line)) {
                Object object = clazz.newInstance();
                String jsonStr = dataToJsonStr(line, templateName);
                object = jsonStrToBean(object, jsonStr);
                tList.add((T) object);
                line = br.readLine();
            }
            return tList;
        } catch (UnsupportedEncodingException e) {
            logger.info("The Character Encoding is not supported:" + e);
            throw new Exception("The Character Encoding is not supported:" + e);
        } catch (FileNotFoundException e) {
            logger.info("open the file denoted by a specified pathname has failed:" + e);
            throw new Exception("open the file denoted by a specified pathname has failed:" + e);
        } catch (IOException e) {
            logger.info("I/O operations has faile:" + e);
            throw new Exception("I/O operations has faile:" + e);
        } catch (IllegalArgumentException e) {
            logger.info(" an illegal or inappropriate argument:" + e);
            throw new Exception("an illegal or inappropriate argument:" + e);
        } finally {
            if (Objects.nonNull(br)) {
                br.close();
            }
            if (Objects.nonNull(reader)) {
                reader.close();
            }
        }
    }

    /**
     * 数据转换成json字符串
     *
     * @param data
     * @return
     */
    private static String dataToJsonStr(String data, String templateName) {
        String[] dataArray = data.split("\\" + defaultSeparator);
        Map<String, Object> fieldMap = new HashMap<>();
        String baseKey = "field";
        for (int i = 0; i < dataArray.length; i++) {
            fieldMap.put(baseKey + (i + 1), replaceBlank(dataArray[i]));
        }
        return Bean2TemplateXmlUtility.getTemplate(templateName, fieldMap);
    }

    /**
     * json转换bean
     *
     * @param t
     * @param jsonStr
     * @return
     */
    @SuppressWarnings("unchecked")
    private static <T> T jsonStrToBean(Object t, String jsonStr) {
        t = JSON.parseObject(jsonStr, t.getClass());
        return (T) t;

    }

    /**
     * 去除空格
     *
     * @param str
     * @return
     */
    private static String replaceBlank(String str) {
        if (StringUtil.isEmpty(str)) {
            return "";
        }
        return str.replaceAll("\\s", "").replaceAll("\\\\", "\\\\\\\\").replaceAll("\"","\'");
    }
}
